import pymysql
def select_all_from_database(time_tuple):
    conn = pymysql.connect(host='204.44.75.153',
                           port=3306,
                           user='root',  # 根据实际情况修改
                           passwd='1233',  # 根据实际情况修改
                           db='mysql',
                           use_unicode=True,
                           charset='utf8mb4')
    cur = conn.cursor()
    cur.execute("USE youxinbei")
    cur.execute("SELECT date, avg_temperature, sum_sunshine FROM db_sunshinetime "
                "WHERE date between %s and %s", (time_tuple[0], time_tuple[1]))
    # cur.execute("SELECT t.date, t.avg_temperature, s.sum_sunshine FROM db_temperature t,db_sunshinetime s "
    #             "WHERE t.date = s.date and t.date between %s and %s", (time_tuple[0], time_tuple[1]))
    # 获取所有记录列表
    results = cur.fetchall()
    # 加入到结果列表results_list
    results_list = []
    for row in results:
        results_list.append((row[0],row[1],row[2]))
    return results_list

# 获取末花期次日到昨天这段时间里的天气数据
def getData(dayBegin):
    import datetime
    dayCur = (datetime.datetime.now() - datetime.timedelta(days = 1)).strftime("%Y-%m-%d")      # 获取当前时间

    #todo  数据库方面的函数，传入参数为【dayBegin】和【dayCur】，均为"%Y-%m-%d"格式的字符串
    # 返回数据记录格式如下：（日期，日平均气温，日照时长）
    # ！！！此处需要插入函数

    data = select_all_from_database((dayBegin,dayCur));
    # data = [("2022-01-12",10,10),
    #         ("2022-01-13",15,9),
    #         ("2022-01-14",20,10)]
    #todo 结束todo

    return data


# 获取提交的末花期，转换为末花期次日
def getDayBegin(dayBegin):
    import datetime

    dayHandIn = datetime.datetime.strptime(dayBegin, "%Y-%m-%d")

    return (dayHandIn + datetime.timedelta(days = 1)).strftime("%Y-%m-%d")


def getX1X2(data):
    X1 = 0          # 有效积温
    X2 = 0          # 累计日照时数

    for record in data:
        X1 += record[1]
        X2 += record[2]

    return X1, X2



def getCurG(dayBegin):
    tarG = 8.00     # 默认目标成熟度
    wb1 = 0.28      # 成熟熵的权重1
    wb2 = 0.72      # 成熟熵的权重2

    X1, X2 = getX1X2(getData(getDayBegin(dayBegin)))      # 有效积温、累计日照时数

    H = wb1 * X1 + wb2 * X2      # 成熟熵
    curG = -3.9875 + 0.0060 * H      # 当前可溶性形物含量
    return curG, ("%.4f" % (curG/tarG)), round(curG/tarG,4)     # 返回当前成熟度，以及成熟进度